ema <- function(signal, period){
	#Inicializar el vector todos los elementos en cero
	ema = 0 * signal;
	
	#Armo la constante
	k <- 2 / ( period + 1);
	
	#Genero el EMA
	for(i in 2:length(signal)){
		ema[i] = signal[i] * k + ema[i-1] * (1-k)
	}
	
	ema
}

ma <- function(f, periods){
	filter(f, rep(1/periods, periods))
}

graficar <- function(f, color) {
	plot(f, type="l", col=color, axes=FALSE, ann=FALSE);
	axis(1, c(1, floor(length(f)/2), length(f)), tsData$Date[c(1, floor(length(f)/2), length(f))], FALSE)
	axis(2)
	box() 
}

generarPNG <- function(name, f1, cols, f2) {
	png(name, width=520, height=420)
	graficar(f1, cols[1])
	if (length(cols) > 1) {
		lines(f2, col=cols[2])		
	}
	dev.off()
}

MACD <- function(closePrices, longPeriod){
	longEMA <- ema(closePrices, longPeriod);
	shortEMA <- ema(closePrices, floor(longPeriod/2));
	macd <- shortEMA - longEMA;
	signal <- ema(macd, 9);
	histogram <- macd - signal;
	
	r <- list(longEMA=longEMA, shortEMA=shortEMA, macd=macd, signal=signal, histogram=histogram);
	r
}

tsData <- read.csv("table.csv");
closePrices <- tsData$Close;

generarPNG("Graficos\ R/PreciosCierre.png", closePrices, "black")

ma17 <- ma(closePrices, 17);
generarPNG("Graficos\ R/ma17.png", ma17, "black")

macdPeriods <- c(10,15,17,34,40,60,80,90);
for(i in 1:length(macdPeriods)){
	r <-  MACD(closePrices, macdPeriods[i]);
	generarPNG(paste("Graficos\ R/Long", macdPeriods[i], ".png"), r$longEMA, "black");
	generarPNG(paste("Graficos\ R/Short", macdPeriods[i], ".png"), r$shortEMA, "black");
	generarPNG(paste("Graficos\ R/macd", macdPeriods[i], ".png"), r$macd, "black");
	generarPNG(paste("Graficos\ R/signal", macdPeriods[i], ".png"), r$signal, "black");
	generarPNG(paste("Graficos\ R/MACD y Signal", macdPeriods[i], ".png"), r$macd, c("blue", "red"), r$signal);
	generarPNG(paste("Graficos\ R/histogram", macdPeriods[i], ".png"), r$histogram, "black");
}